//
//  SQLiteManager.swift
//  FMDB演练
//
//  Created by teacher on 16/5/3.
//  Copyright © 2016年 teacher. All rights reserved.
//

import UIKit

private let DB_NAME = "status.db"

class SQLiteManager: NSObject {
    
    static let sharedManger = SQLiteManager()
    
    // 全局数据库操作队列
    var queue: FMDatabaseQueue!
    
    override init(){
        super.init()
        
        // 0. 数据库路径 
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(DB_NAME)
        
        print(path)
        // 1. 打开数据库
        queue = FMDatabaseQueue(path: path)
        
        // 2. 创建表
        createTabel()
    }
    
    
    /// 创建表
    private func createTabel(){
        
        // 读取sql语句所在的路径
        let sqlPath = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
        
        // 读取sql语句
        let sql = (try! NSString(contentsOfFile: sqlPath, encoding: NSUTF8StringEncoding)) as String
        
        // 2. 创建表
        queue.inDatabase { (db) -> Void in
            if db.executeUpdate(sql, withArgumentsInArray: nil) {
                print("建表成功")
            }else{
                print("建表失败")
            }
        }
    }
    
    
    /// 从数组库里面查询出一系列数据出来，每一条数据的格式是字典
    ///
    /// - parameter sql: <#sql description#>
    ///
    /// - returns: <#return value description#>
    func execRecordSet(sql: String) -> [[String: AnyObject]]{
        // 定义返回值的数组
        var result = [[String: AnyObject]]()
        
        SQLiteManager.sharedManger.queue.inDatabase { (db) -> Void in
            let rs = db.executeQuery(sql, withArgumentsInArray: nil)
            
            // 查询是否有下一条数据
            while rs.next() {
                
                var dict = [String: AnyObject]()
                
                // 把数据的内容封装成字典
                // 列名为Key，值为 Value
                // 遍历这一行数据的列数
                for i in 0..<rs.columnCount() {
                    // 取每一列的Key和value
                    let key = rs.columnNameForIndex(i)
                    let value = rs.objectForColumnIndex(i)
                    
                    dict[key] = value
                }
                // 将该条数据所对应的字典添加到数组里面去
                result.append(dict)
            }
        }
        return result
    }

}
